namespace Launcher.View

import System

import Launcher.Model

class RankingViewModel:
"""Description of RankingViewModel"""
	_model as StartMenuModel
	_actualPage as int
	_numberOfItemsInFirstLine as int
	_maxNumberOfLines as int

	event ItemChanged as RankingItemChangedHandler
	event ItemSizeChanged as RankingItemSizeChangedHandler

	[getter(Pages)]
	_pages = []

	SelectedPage as RankingViewPage:
		get:
			return _pages[_actualPage]
	
	def constructor(model as StartMenuModel):
		_model = model
		_model.Sort()
		Paginate(6, 3)
		
	def Paginate(numberOfItemsInFirstLine as int, maxNumberOfLines as int):
		_numberOfItemsInFirstLine = numberOfItemsInFirstLine
		_maxNumberOfLines = maxNumberOfLines
		
		_actualPage = 0
		
		numberOfModelItems = _model.Applications.Count
		numberOfItems = CalculateNumberOfItems(numberOfItemsInFirstLine, maxNumberOfLines)
		numberOfPages = numberOfModelItems / numberOfItems
		if (numberOfModelItems % numberOfItems) != 0: 
			numberOfPages++

		_pages = [CreatePage(i, numberOfItems) for i in range(numberOfPages)]
			
	private def CalculateNumberOfItems(numberOfItemsInFirstLine as int, maxNumberOfLines as int):
		return 1 + numberOfItemsInFirstLine * CalculateNumberOfBlocks(maxNumberOfLines)
		
	private def CalculateNumberOfBlocks(numberOfLines as int) as int:
		if numberOfLines == 1: return 1
		return CalculateNumberOfBlocks(numberOfLines - 1) + numberOfLines
		
	private def CreatePage(pageNumber as int, numberOfItems as int):
		startPos = pageNumber * numberOfItems
		endPos = startPos + numberOfItems
		if endPos > len(_model.Applications): endPos = len(_model.Applications)

		page = RankingViewPage(_model.Applications[startPos: endPos])
		page.RankingItemChanged += _OnItemChanged
		page.RankingItemSizeChanged += _OnItemSizeChanged
		return page
		
	private def _OnItemChanged(item as RankingViewItem):
		ItemChanged(item)
		
	private def _OnItemSizeChanged(item as RankingViewItem):
		ItemSizeChanged(item)
		
	def Repaginate():
		_model.Sort()
		Paginate(_numberOfItemsInFirstLine, _maxNumberOfLines)

	def Next():
		if IsLast(): return false
		_actualPage++
		return true
		
	def Previous():
		if IsFirst(): return false
		_actualPage--
		return true
	
	def IsFirst():
		return _actualPage == 0
	
	def IsLast():
		return _actualPage == len(_pages) - 1
